<?php
/**
 * Created by PhpStorm.
 * User: yangos
 * Date: 18-6-18
 * Time: 上午3:26
 */

namespace vola\log\device;


use vola\Container;
use vola\log\Logger;

class File extends Logger {

    public $loglist = [];

    public function log($name, $message = '',$level = 'info', array $context = array())
    {
        // TODO: Implement log() method.
        $replce = [];
        if (!empty($context)) {
            foreach ($context as $item => $value) {
                $replce['{' . $item . '}'] = $value;
            }
        }
        array_push($this->loglist, [
            '%name%'  => $name,
            '%level%' => $level,
            '%message%' => strtr($message, $replce),
            '%date%' => date('Y-m-d H:i:s', time()),
            '%timestamp%' => microtime(true),
        ]);
    }

    public function save()
    {
        // TODO: Implement save() method.
        $template = Container::get('app')->config('log_template');
        if (empty($template)) {
            $template = '%date% | %level% | %timestamp% | %name% | %message%';
        }
        $context = '';
        foreach ($this->loglist as $log) {
            $context .= strtr($template, $log) . PHP_EOL;
        }

        $path = Container::get('app')->getRuntimepath() . date('Y/m/d') . '.log';
        if (!is_dir(dirname($path))) {
            mkdir(dirname($path), 0755, true);
            file_put_contents(dirname($path) . '/index.html', '');
            file_put_contents(dirname(dirname($path)) . '/index.html', '');
        }

        file_put_contents($path, $context . PHP_EOL, FILE_APPEND);
    }
}